<?php
//by willson 105328468@qq.com 2014/10/13
//member module interface

class member extends core {
	private $order_mod;

	public function __construct() {
		$this->order_mod = m("order");
		parent::__construct();
	}

	//首页会员首页接口，在登录时数据已经取到
	public function index() {
		$sign = (isset($_GET['sign']) && trim($_GET['sign'])) ? trim($_GET['sign']) : '';
		$not_pay = $not_shipping = $not_confirm = $not_comment = $notify = 0; //$notify供微信端用
		$member = null;
		if ($this->member_id) {
			if ($sign) {
				$sql = "SELECT count(*) FROM jf_member WHERE sign='{$sign}' AND id='{$this->member_id}'";
				$exists = intval($this->db->get_var($sql));
				if ($exists==0) {
					error("该账号已在其他设备登录", -9);
				}
			}
			$not_pay = $this->_get_one_status_order(0, $this->member_id);
			$not_shipping = $this->_get_one_status_order(1, $this->member_id);
			$not_confirm = $this->_get_one_status_order(2, $this->member_id);
			$not_comment = $this->_get_one_status_order(3, $this->member_id);
			$sql = "SELECT count(*) FROM jf_message WHERE member_id='{$this->member_id}' AND message_type='member' AND readed='0'";
			$notify = $this->db->get_var($sql);
			//获取会员所有信息
			$sql = "SELECT * FROM jf_member WHERE id='{$this->member_id}'";
			$member = $this->db->get_row($sql);
		}
		// 重新获取积分，修改session,用于查看积分
		if($member){
			$_SESSION['member']->integral = $member->integral;
		}
		
		//获取购物车总数
		/*$sql = "SELECT IFNULL(SUM(quantity),0) FROM jf_cart WHERE 1";
		if ($this->member_id>0) {
			$sql .= " AND (member_id='{$this->member_id}' OR session_id='".session_id()."')";
		} else {
			$sql .= " AND session_id='".session_id()."'";
		}
		$cart_total = $this->db->get_var($sql);
		$coupon_count = $this->_get_coupon_count();*/
		success(array("member_id" => $this->member_id,
			/*"cart_total" => $cart_total,
			"coupon_count" => $coupon_count,
			"not_pay" => $not_pay,
			"not_shipping" => $not_shipping,
			"not_confirm" => $not_confirm,
			"not_comment" => $not_comment,*/
			"notify" => $notify,
			"member" => $member,
		));
	}
	
	//个人资料
	public function edit() {
		//微信JSSDK，在微信端读取
		if ($this->is_weixin()) {
			$url = '';
			if (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest") {
				$url = "http://$_SERVER[HTTP_HOST]/wap.php";
			}
			require_once(FRAMEWORK_PATH . '/class/wxapi/config.php');
			require_once(FRAMEWORK_PATH . '/class/wxapi/jssdk.php');
			$weixin_jssdk = new JSSDK(WX_APPID, WX_SECRET);
			$weixin_sign_package = $weixin_jssdk->getSignPackage($url);
			$this->smarty->assign('weixin_sign_package', $weixin_sign_package);
		}
		success('ok');
	}
	
	//我的二维码
	public function code() {
		if ($this->member_id>0) {
			include_once(FRAMEWORK_PATH . "/third/phpqrcode/phpqrcode.php");
			$url = urldecode("{$this->domain}/wap.php?app=member&act=detail&invite_code=".$_SESSION['member']->invite_code);
			QRcode::png($url);
		}
		exit;
	}

	//优惠券总数
	private function _get_coupon_count() {
		$sql = "SELECT count(*) FROM jf_coupon_sn WHERE status='1' AND member_id='{$this->member_id}' AND member_id>'0'";
		//echo $sql;
		$num = intval($this->db->get_var($sql));
		return $num;
	}
	
	public function _get_one_status_order($status, $member_id) {
		$sql = "SELECT count(*) FROM jf_order WHERE status='{$status}' AND member_id='{$this->member_id}' AND see = 1";
		$num = intval($this->db->get_var($sql));
		return $num;
	}

	/* 20150715 by ajsong 废弃，与 passport::check_sign() 综合在一起 */
	//首页会员首页获取即时的收入
	public function total_income() {
		$sql = "SELECT total_income FROM {$this->tbp}member WHERE id='{$this->member_id}'";
		$total_income = $this->db->get_var($sql);
		success($total_income);
	}

	//上传头像
	public function avatar() {
		$avatar = upload_one_file('avatar', 'avatar');
		if (!$avatar) error('头像上传失败');
		//$avatar = (isset($_POST['avatar']) && trim($_POST['avatar'])) ? trim($_POST['avatar']) : '';
		$sql = "UPDATE {$this->tbp}member SET avatar='{$avatar}' WHERE id='{$this->member_id}'";
		$this->db->query($sql);
		$avatar = add_domain($avatar);
		//$avatar .= "!logo"; //logo缩略图 by willson 2015/9/6
		$_SESSION['member']->avatar = $avatar;
		success($avatar);
	}

	//微信端上传头像
	public function wx_avatar() {
		global $image_domain;
		$image_id = (isset($_POST['avatar']) && trim($_POST['avatar'])) ? trim($_POST['avatar']) : '';
		require_once(FRAMEWORK_PATH . '/class/wxapi/config.php');
		//下载微信图片
		$avatar = '';
		if($image_id!=''){
			$wxapi = new wechatCallbackAPI();
			$access_token = $wxapi->access_token(); //获取access_token
			$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$image_id}";
			$data = $wxapi->downloadFile($url);
			$savename = date("Ymd").rand(10000,99999).'.jpg';
			$path = '/uploadfiles/avatar/'.date("Ymd").'/';
			$wxapi->makeDir($path);
			$hardpath = $_SERVER['DOCUMENT_ROOT'].$path;
			$fullpath = $hardpath.$savename;
			$handle = @fopen($fullpath, 'w') or error('Unable to write file!');
			@fwrite($handle, $data['body']);
			@fclose($handle);
			/*//
			//上传到又拍云
			require_once(FRAMEWORK_PATH . '/upyun/upyun.class.php');
			$upyunDomain = $image_domain; //又拍云上传网址
			$upyunBucket = 'yidian2015'; //又拍云上传空间
			$upyunUser = 'qizi'; //又拍云账号
			$upyunPass = 'aVEgvBQkzCAWNoq4WVWq'; //又拍云密码
			$upyunPath = '/uploadfiles/avatar'; //又拍云上传文件夹
			$upyun = new UpYun($upyunBucket, $upyunUser, $upyunPass);
			$upyunPathname = $upyunPath.'/'.date('Y').'/'.date('m').'/'.date('d').'/'.$savename;
			//$fh = fopen($path, 'rb');
			$rsp = $upyun->writeFile($upyunPathname, $data['body'], true);
			//fclose($fh);
			$avatar = $upyunDomain.$upyunPathname;
			//unlink($path);
			//*/
			$avatar = $path.$savename;
		}
		if (!$avatar) error('头像上传失败');
		$sql = "UPDATE {$this->tbp}member SET avatar='{$avatar}' WHERE id='{$this->member_id}'";
		$this->db->query($sql);
		$avatar = add_domain($avatar);
		$_SESSION['member']->avatar = $avatar;
		success($avatar);
	}

	//修改个人资料
	public function edit_info() {
		if (isset($_POST['name']) && trim($_POST['name'])) {
			$name = trim($_POST['name']);
			$sql = "SELECT count(*) FROM jf_member WHERE name='{$name}' AND id<>'{$this->member_id}'";
			$exists = intval($this->db->get_var($sql));
			if ($exists > 0) {
				error("名称已经存在");
			}
		}
		$fields = array("real_name", "nick_name", "mobile", "qq", "weixin", "name",
			"birth_year", "birth_month", "birth_day", "avatar", "sex");
		$set_sql = "";
		foreach ($fields as $field) {
			if (isset($_POST[$field])) {
				$value = trim($_POST[$field]);
				if ($set_sql) {
					$set_sql .= ", `{$field}`='{$value}'";
				} else {
					$set_sql = "`{$field}`='{$value}'";
				}
				$_SESSION['member']->$field = $value;
			}
		}
		if ($set_sql) {
			$sql = "UPDATE jf_member SET {$set_sql} WHERE id='{$this->member_id}'";
			//echo $sql;
			$this->db->query($sql);
		}
		//加入以下代码，会导致shop_id丢失
		//12/30
		$this->_reload_session_info();
		$sql = "SELECT * FROM jf_member WHERE id='{$this->member_id}'";
		$row = $this->db->get_row($sql);
		success($row);
	}

	//发送反馈
	public function feedback() {
		$type_id = (isset($_POST['type_id']) && intval($_POST['type_id'])) ? intval($_POST['type_id']) : 0;
		$content = (isset($_POST['content']) && trim($_POST['content'])) ? trim($_POST['content']) : '';
		$sql = "INSERT INTO jf_feedback(member_id, content, add_time, ip, type_id)
			VALUES('{$this->member_id}', '{$content}', '".time()."', '".ip()."', '{$type_id}')";
		$this->db->query($sql);
		success('ok');
	}

	//修改密码
	public function password() {
		require_once(FRAMEWORK_PATH . "/third/emchat/Easemob.class.php");
		$origin_password = (isset($_POST['origin_password']) && trim($_POST['origin_password'])) ? trim($_POST['origin_password']) : '';
		$new_password = (isset($_POST['new_password']) && trim($_POST['new_password'])) ? trim($_POST['new_password']) : '';
		if ($new_password == '') error('密码不能为空');
		$sql = "SELECT password, salt FROM jf_member WHERE id='{$this->member_id}'";
		$member = $this->db->get_row($sql);
		if ($member) {
			if ($member->password!=crypt_password($origin_password, $member->salt)) error('旧密码错误');
			$salt = rand(100000,999999);
			$crypt_password = md5(md5($new_password).$salt);
			$sql = "UPDATE jf_member SET password='{$crypt_password}', salt='{$salt}' WHERE id='{$this->member_id}'";
			$this->db->query($sql);
			$this->_reload_session_info();
		}
		success('ok');
	}

	//我的订单列表
	//0：未支付，1：已支付，2：已发货，3：完成（已收货），4：完成（已评价），-1：取消，-2：退款，-3：退货
	public function order() {
		$status = isset($_GET['status']) ? trim($_GET['status']) : '';
		//积分商城订单
		$integral_order = (isset($_GET['integral_order']) && trim($_GET['integral_order'])) ? intval($_GET['integral_order']) : 0;
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 100;
		$where = " AND o.member_id='{$this->member_id}'";
		if ($status!='') {
			if ($status=='-2,-3') {
				$where .= " AND (o.status IN ({$status}) OR o.ask_refund_time>0)";
			} else {
				$where .= " AND o.status IN ({$status})";
			}
		}
		$where .= " AND o.integral_order='{$integral_order}'";

		$sql = "SELECT o.*, '' as shop_name FROM jf_order o
			WHERE 1 {$where} ORDER BY o.id DESC LIMIT {$offset},{$pagesize}";
		//echo $sql;
		$orders = $this->db->get_results($sql);
		if ($orders) {
			foreach ($orders as $k=>$o) {
				$sql = "SELECT og.*, g.integral, g.stocks, g.price as goods_price, g.promote_price as goods_promote_price
						FROM jf_order_goods og LEFT JOIN jf_goods g ON og.goods_id=g.id WHERE order_id='{$o->id}'";
				$goods = $this->db->get_results($sql);
				$goods = add_domain_deep($goods, array("goods_pic"));
				$orders[$k]->goods = $goods;
			}
		}
		success($orders);
	}

	//订单详情
	public function order_detail() {
		$order_sn = (isset($_GET['order_sn'])) ? $_GET['order_sn'] : '';
		$order_id = (isset($_GET['id']) && intval($_GET['id'])) ? intval($_GET['id']) : 0;
		$where = " (o.order_sn='{$order_sn}' OR o.parent_order_sn='{$order_sn}')";
		if ($order_id>0) $where = " o.id='{$order_id}'";
		$sql = "SELECT o.*, '' as shop_name, 0 as shop_member_id, '' as shop_mobile, '' as shop_avatar
			FROM jf_order o
			WHERE {$where} AND o.member_id='{$this->member_id}'";
		//exit($sql);
		$order = $this->db->get_row($sql);
		if ($order) {
			//更新订单已阅读
			$sql = "UPDATE jf_order o SET see = 0 WHERE {$where} AND o.member_id='{$this->member_id}'";
			$this->db->query($sql);

			$sql = "SELECT og.*, g.integral, g.stocks, g.price as goods_price, g.promote_price as goods_promote_price
					FROM jf_order_goods og LEFT JOIN jf_goods g ON og.goods_id=g.id WHERE order_id='{$order->id}'";
			$goods = $this->db->get_results($sql);
			$goods = add_domain_deep($goods, array("goods_pic"));
			//兼容积分订单有规格
			if ($goods) {
				foreach ($goods as $k=>$g) {
					$sql = "SELECT price FROM jf_goods_spec WHERE goods_id='{$g->goods_id}' AND spec='{$g->spec}' ORDER BY id ASC";
					$r = $this->db->get_row($sql);
					if ($r) $goods[$k]->integral = intval($r->price);
				}
			}
			$order->goods = $goods;
			//退货退款申请
			$sql = "SELECT * FROM jf_order_refund WHERE order_id='{$order->id}' ORDER BY id DESC";
			$g = $this->db->get_row($sql);
			if ($g) {
				$g->add_time = date('Y-m-d H:i:s', $g->add_time);
				$g->audit_time = date('Y-m-d H:i:s', $g->audit_time);
			}
			$order->refund = $g;
			$order->add_time_str = date('Y-m-d H:i:s', $order->add_time);
			$order->pay_time_str = date('Y-m-d H:i:s', $order->pay_time);
			$order->shipping_time_str = date('Y-m-d H:i:s', $order->shipping_time);
			$order->shouhuo_time_str = date('Y-m-d H:i:s', $order->shouhuo_time);
			$order->delay_shouhuo_days = $this->configs['delay_shouhuo_days'];
		}
		success($order);
	}

	//物流情况
	public function order_express() {
		$order_id = (isset($_GET['id']) && intval($_GET['id'])) ? intval($_GET['id']) : 0;
		if ($order_id<=0) error('数据错误');
		$sql = "SELECT *, '' as express FROM jf_order WHERE id='{$order_id}' AND member_id='{$this->member_id}'";
		$order = $this->db->get_row($sql);
		if ($order) {
			$sql = "SELECT og.*, g.stocks, g.price as goods_price 
				FROM jf_order_goods og LEFT JOIN jf_goods g ON og.goods_id=g.id WHERE order_id='{$order->id}'";
			$goods = $this->db->get_results($sql);
			$goods = add_domain_deep($goods, array("goods_pic"));
			$order->goods = $goods;
			$express = getkdniao($order->shipping_company, $order->shipping_number);
			if (is_array($express)) $express = array_reverse($express);
			$order->express = $express;
		}
		// var_dump($order->express);exit;
		success($order);
	}

	//订单退款
	public function order_refund() {
		$order_sn = (isset($_GET['order_sn'])) ? $_GET['order_sn'] : '';
		if (!$order_sn) exit;
		
		$sql = "SELECT * FROM jf_order WHERE order_sn='{$order_sn}'";
		$order = $this->db->get_row($sql);
		if (!$order) exit;
		
		$out_refund_no = generate_order_sn();
		include_once(FRAMEWORK_PATH . "/class/wxapi/WxPayPubHelper/WxPayPubHelper.php");
		$refundApi = new Refund_pub();
		$refundApi->setParameter("out_trade_no", $order->order_sn); //原订单号
		$refundApi->setParameter("total_fee", $order->total_price*100); //订单金额
		$refundApi->setParameter("refund_fee", $order->total_price*100); //退款金额
		$refundApi->setParameter("op_user_id", WxPayConf_pub::MCHID); //操作员账号，一般为商户号
		$refundApi->setParameter("out_refund_no", $out_refund_no); //退款订单号
		print_r($refundApi->getResult());
		exit;
		//$sql = "INSERT INTO jf_order_refund (order_id, out_refund_no, refund_fee, status, add_time)
		//		VALUES ('{$order->id}', '{$out_refund_no}', '{$order->total_price}', '0', '".time()."')";
		//$this->db->query($sql);
	}

	//消费明细，读取1：已支付，2：已发货，3：完成（已收货），4：完成（已评价）这些订单
	public function xfmx() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 100;
		$where = "o.member_id='{$this->member_id}' AND o.status in (1, 2, 3, 4)";
		$sql = "SELECT o.id, o.order_sn, o.add_time, s.name as shop_name FROM jf_order o LEFT JOIN jf_shop s ON o.factory_shop_id=s.id
			WHERE {$where} ORDER BY o.id DESC LIMIT {$offset},{$pagesize}";
		//echo $sql;
		$orders = $this->db->get_results($sql);
		if ($orders) {
			foreach ($orders as $k=>$o) {
				$orders[$k]->add_time = date('Y-m-d', $o->add_time);
			}
		}
		success($orders);
	}

	//我的订单的支付,微信端用
	public function order_pay() {
		$order_sn = (isset($_POST['order_sn']) && trim($_POST['order_sn'])) ? trim($_POST['order_sn']) : '';
		$order_price = (isset($_POST['price']) && trim($_POST['price'])) ? floatval($_POST['price']) : 0;
		$order_body = (isset($_POST['body']) && trim($_POST['body'])) ? trim($_POST['body']) : '';
		$re_order_sn = (isset($_POST['re_order_sn']) && trim($_POST['re_order_sn'])) ? trim($_POST['re_order_sn']) : '';
		if ($order_sn!='') {
			$sql = "UPDATE jf_order SET parent_order_sn='{$order_sn}' WHERE order_sn='{$order_sn}'";
			$this->db->query($sql);
		}
		if ($order_sn=='' || $order_price<=0) {
			$order_sn = (isset($_SESSION['order_sn']) && trim($_SESSION['order_sn'])) ? trim($_SESSION['order_sn']) : '';
			$order_price = (isset($_SESSION['order_price']) && trim($_SESSION['order_price'])) ? floatval($_SESSION['order_price']) : 0;
			$order_body = (isset($_SESSION['order_body']) && trim($_SESSION['order_body'])) ? trim($_SESSION['order_body']) : '';
		}
		if ($order_sn=='' || $order_price<=0) {
			error('订单信息错误！');
		}
		//重新付款需要重写订单号,微信必须这么做
		if ($re_order_sn!='') {
			$origin_order_sn = $order_sn;
			$order_sn = generate_order_sn();
			$sql = "UPDATE jf_order SET order_sn='{$order_sn}' WHERE order_sn='{$origin_order_sn}'";
			$this->db->query($sql);
		}
		$_SESSION['order_sn'] = $order_sn;
		$_SESSION['order_price'] = $order_price;
		$_SESSION['order_body'] = $order_body;
		
		//确保库存足够
		$sql = "SELECT g.* FROM jf_order_goods g LEFT JOIN jf_order o ON o.id=g.order_id WHERE o.order_sn='{$order_sn}'";
		$goods = $this->db->get_results($sql);
		foreach ($goods as $k => $g) {
			$sql = "SELECT g.*, '' as spec, 0 as quantity
				FROM jf_goods g INNER JOIN jf_goods_spec gs ON g.id=gs.goods_id
				WHERE g.id='{$g->goods_id}' AND gs.spec='{$g->spec}'";
			//echo $sql;
			$row = $this->db->get_row($sql);
			if ($row) {
				$name = mb_substr($row->name, 0, 6);
				if ($g->quantity > $row->stocks) {
					error("商品（{$name}）库存不足");
				}
			}
		}
		
		/**
		 * JS_API支付demo
		 * ====================================================
		 * 在微信浏览器里面打开H5网页中执行JS调起支付。接口输入输出数据格式为JSON。
		 * 成功调起支付需要三个步骤：
		 * 步骤1：网页授权获取用户openid
		 * 步骤2：使用统一支付接口，获取prepay_id
		 * 步骤3：使用jsapi调起支付
		*/
		include_once(FRAMEWORK_PATH . "/class/wxapi/WxPayPubHelper/WxPayPubHelper.php");
		
		//使用jsapi接口
		$jsApi = new JsApi_pub();
		
		//=========步骤1：网页授权获取用户openid============
		//通过code获得openid
		$openid = '';
		if (!isset($_GET['code'])){
			//触发微信返回code码
			$url = $jsApi->createOauthUrlForCode(urlencode("http://".$_SERVER['SERVER_NAME']."/wap.php?app=member&act=order_pay"));
			header("location: $url");
		}else{
			//获取code码，以获取openid
			$code = $_GET['code'];
			$jsApi->setCode($code);
			$openid = $jsApi->getOpenid();
		}
		
		//=========步骤2：使用统一支付接口，获取prepay_id============
		//使用统一支付接口
		$unifiedOrder = new UnifiedOrder_pub();
		
		//设置统一支付接口参数
		//设置必填参数
		//appid已填,商户无需重复填写
		//mch_id已填,商户无需重复填写
		//noncestr已填,商户无需重复填写
		//spbill_create_ip已填,商户无需重复填写
		//sign已填,商户无需重复填写
		$unifiedOrder->setParameter("openid", "$openid");
		$unifiedOrder->setParameter("body", "$order_body");//商品描述
		if($order_sn==''){
			//自定义订单号，此处仅作举例
			$timeStamp = time();
			$order_sn = WxPayConf_pub::APPID."$timeStamp";
		}
		$unifiedOrder->setParameter("out_trade_no", "$order_sn");//商户订单号
		$unifiedOrder->setParameter("total_fee", $order_price*100);//总金额,单位:分
		$unifiedOrder->setParameter("notify_url", "http://".$_SERVER['SERVER_NAME']."/wx_notify_url.php");//通知地址
		$unifiedOrder->setParameter("trade_type", "JSAPI");//交易类型
		//非必填参数，商户可根据实际情况选填
		//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
		//$unifiedOrder->setParameter("device_info","XXXX");//设备号
		//$unifiedOrder->setParameter("attach","XXXX");//附加数据
		//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
		//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
		//$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
		//$unifiedOrder->setParameter("openid","XXXX");//用户标识
		//$unifiedOrder->setParameter("product_id","XXXX");//商品ID
		
		$prepay_id = $unifiedOrder->getPrepayId();
		//=========步骤3：使用jsapi调起支付============
		$jsApi->setPrepayId($prepay_id);
		
		$jsApiParameters = $jsApi->getParameters();
		//exit($jsApiParameters);
		
		success( $jsApiParameters, '成功', 0, array('order_sn'=>$_SESSION['order_sn']) );
		$_SESSION['order_sn'] = '';
		$_SESSION['order_price'] = '';
		$_SESSION['order_body'] = '';
	}

	//修改订单价格
	public function order_change_price() {
		$order_id = (isset($_POST['id']) && intval($_POST['id'])) ? intval($_POST['id']) : 0;
		$price = (isset($_POST['price']) && floatval($_POST['price'])) ? floatval($_POST['price']) : 0;
		if ($order_id) {
			$sql = "SELECT status FROM jf_order WHERE id='{$order_id}' AND shop_id='{$this->shop_id}'";
			$status = intval($this->db->get_var($sql));
			if ($status!=0) error('只有未支付的订单才能修改价格');
			$sql = "UPDATE jf_order SET total_price='{$price}' WHERE id='{$order_id}' AND shop_id='{$this->shop_id}'";
			$this->db->get_row($sql);
		}
		success("ok");
	}

	//取消订单
	public function order_cancel() {
		$id = (isset($_POST['id']) && trim($_POST['id'])) ? intval($_POST['id']) : 0;
		$sql = "SELECT * FROM jf_order WHERE id='{$id}' AND member_id='{$this->member_id}'";
		$row = $this->db->get_row($sql);
		if($this->member_id != $row->member_id) error('该订单用户不匹配');
		if($row->status != 1) error('该订单不可取消');
		//设置状态
		$sql = "UPDATE jf_order SET status='-1' WHERE id='{$id}' AND member_id='{$this->member_id}'";
		$this->db->query($sql);
		//退回积分
		$sql = "UPDATE jf_member SET integral= integral + {$row->total_price} WHERE id ='{$this->member_id}'";
		$this->db->query($sql);
		//写入积分流水
		$sql = "INSERT INTO jf_member_integral_history (member_id,type,order_sn,integral,add_time,status) VALUES ('{$this->member_id}','3','{$row->order_sn}','{$row->total_price}','".time()."',1)";
		$this->db->query($sql);

		success('ok');
	}

	//咖啡订单列表
	//0：未支付，1：已支付，2：已发货，-1：取消
	public function coffee_order() {
		$status = isset($_GET['status']) ? trim($_GET['status']) : '';
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 100;
		$where = " AND o.member_id='{$this->member_id}'";
		if ($status!='') {
			if ($status=='-2,-3') {
				$where .= " AND (o.status IN ({$status}) OR o.ask_refund_time>0)";
			} else {
				$where .= " AND o.status IN ({$status})";
			}
		}

		$sql = "SELECT o.*, '' as shop_name FROM jf_coffee_order o
			WHERE 1 {$where} ORDER BY o.id DESC LIMIT {$offset},{$pagesize}";
		//echo $sql;
		$orders = $this->db->get_results($sql);
		if ($orders) {
			foreach ($orders as $k=>$o) {
				$sql = "SELECT oc.*, c.price as coffee_price
						FROM jf_coffee_order_coffee oc LEFT JOIN jf_coffee c ON oc.coffee_id=c.id WHERE order_id='{$o->id}'";
				$coffees = $this->db->get_results($sql);
				$coffees = add_domain_deep($coffees, array("default_pic"));
				$orders[$k]->coffees = $coffees;
			}
		}
		success($orders);
	}

	//咖啡订单详情
	public function coffee_order_detail() {
		$order_sn = (isset($_GET['order_sn'])) ? $_GET['order_sn'] : '';
		$order_id = (isset($_GET['id']) && intval($_GET['id'])) ? intval($_GET['id']) : 0;
		$where = " (o.order_sn='{$order_sn}' OR o.parent_order_sn='{$order_sn}')";
		if ($order_id>0) $where = " o.id='{$order_id}'";
		$sql = "SELECT o.*, '' as shop_name, 0 as shop_member_id, '' as shop_mobile, '' as shop_avatar
			FROM jf_coffee_order o
			WHERE {$where} AND o.member_id='{$this->member_id}'";
		//exit($sql);
		$order = $this->db->get_row($sql);
		if ($order) {
			$sql = "SELECT oc.*, c.price as coffee_price
					FROM jf_coffee_order_coffee oc LEFT JOIN jf_coffee c ON oc.coffee_id=c.id WHERE order_id='{$order->id}'";
			$coffees = $this->db->get_results($sql);
			$coffees = add_domain_deep($coffees, array("default_pic"));
			$order->coffees = $coffees;
			$order->add_time_str = date('Y-m-d H:i:s', $order->add_time);
			$order->pay_time_str = date('Y-m-d H:i:s', $order->pay_time);
			$order->shipping_time_str = date('Y-m-d H:i:s', $order->shipping_time);
		}
		success($order);
	}

	//取消咖啡订单
	public function coffee_order_cancel() {
		$id = (isset($_POST['id']) && trim($_POST['id'])) ? intval($_POST['id']) : 0;
		$sql = "SELECT shop_id, total_price, status FROM jf_coffee_order WHERE id='{$id}' AND member_id='{$this->member_id}'";
		$row = $this->db->get_row($sql);
		//设置状态
		$sql = "UPDATE jf_coffee_order SET status='-1' WHERE id='{$id}' AND member_id='{$this->member_id}'";
		$this->db->query($sql);
		//减少收入
		if($row->status>0){
			/*
			$total_price = floatval($row->total_price);
			if ($total_price) {
				$sql = "SELECT member_id FROM jf_shop WHERE id='{$row->shop_id}'";
				$member_id = $this->db->get_var($sql);
				$sql = "SELECT total_income FROM jf_member WHERE id='{$member_id}'";
				$total_income = floatval($this->db->get_var($sql));
				if ($total_price >= $total_income) {
					$income = 0;
				} else {
					$income = $total_income - $total_price;
				}
				$sql = "UPDATE jf_member SET total_income={$income} WHERE id='{$member_id}'";
				$this->db->query($sql);
				//echo $income;
				//$_SESSION['member']->total_income = $income;
			}
			*/
		}
		success('ok');
	}

	//咖啡订单的支付,微信端用
	public function coffee_order_pay() {
		$order_sn = (isset($_POST['order_sn']) && trim($_POST['order_sn'])) ? trim($_POST['order_sn']) : '';
		$order_price = (isset($_POST['price']) && trim($_POST['price'])) ? floatval($_POST['price']) : 0;
		$order_body = (isset($_POST['body']) && trim($_POST['body'])) ? trim($_POST['body']) : '';
		$re_order_sn = (isset($_POST['re_order_sn']) && trim($_POST['re_order_sn'])) ? trim($_POST['re_order_sn']) : '';
		if ($order_sn!='') {
			$sql = "UPDATE jf_coffee_order SET parent_order_sn='{$order_sn}' WHERE order_sn='{$order_sn}'";
			$this->db->query($sql);
		}
		if ($order_sn=='' || $order_price<=0) {
			$order_sn = (isset($_SESSION['coffee_order_sn']) && trim($_SESSION['coffee_order_sn'])) ? trim($_SESSION['coffee_order_sn']) : '';
			$order_price = (isset($_SESSION['coffee_order_price']) && trim($_SESSION['coffee_order_price'])) ? floatval($_SESSION['coffee_order_price']) : 0;
			$order_body = (isset($_SESSION['coffee_order_body']) && trim($_SESSION['coffee_order_body'])) ? trim($_SESSION['coffee_order_body']) : '';
		}
		if ($order_sn=='' || $order_price<=0) {
			error('订单信息错误！');
		}
		//重新付款需要重写订单号,微信必须这么做
		if ($re_order_sn!='') {
			$origin_order_sn = $order_sn;
			$order_sn = generate_order_sn();
			$sql = "UPDATE jf_coffee_order SET order_sn='{$order_sn}' WHERE order_sn='{$origin_order_sn}'";
			$this->db->query($sql);
		}
		$_SESSION['coffee_order_sn'] = $order_sn;
		$_SESSION['coffee_order_price'] = $order_price;
		$_SESSION['coffee_order_body'] = $order_body;
		
		/**
		 * JS_API支付demo
		 * ====================================================
		 * 在微信浏览器里面打开H5网页中执行JS调起支付。接口输入输出数据格式为JSON。
		 * 成功调起支付需要三个步骤：
		 * 步骤1：网页授权获取用户openid
		 * 步骤2：使用统一支付接口，获取prepay_id
		 * 步骤3：使用jsapi调起支付
		*/
		include_once(FRAMEWORK_PATH . "/class/wxapi/WxPayPubHelper/WxPayPubHelper.php");
		
		//使用jsapi接口
		$jsApi = new JsApi_pub();
		
		//=========步骤1：网页授权获取用户openid============
		//通过code获得openid
		$openid = '';
		if (!isset($_GET['code'])){
			//触发微信返回code码
			$url = $jsApi->createOauthUrlForCode(urlencode("http://".$_SERVER['SERVER_NAME']."/wap.php?app=member&act=coffee_order_pay"));
			header("location: $url");
		}else{
			//获取code码，以获取openid
			$code = $_GET['code'];
			$jsApi->setCode($code);
			$openid = $jsApi->getOpenid();
		}
		
		//=========步骤2：使用统一支付接口，获取prepay_id============
		//使用统一支付接口
		$unifiedOrder = new UnifiedOrder_pub();
		
		//设置统一支付接口参数
		//设置必填参数
		//appid已填,商户无需重复填写
		//mch_id已填,商户无需重复填写
		//noncestr已填,商户无需重复填写
		//spbill_create_ip已填,商户无需重复填写
		//sign已填,商户无需重复填写
		$unifiedOrder->setParameter("openid", "$openid");
		$unifiedOrder->setParameter("body", "$order_body");//商品描述
		if($order_sn==''){
			//自定义订单号，此处仅作举例
			$timeStamp = time();
			$order_sn = WxPayConf_pub::APPID."$timeStamp";
		}
		$unifiedOrder->setParameter("out_trade_no", "$order_sn");//商户订单号
		$unifiedOrder->setParameter("total_fee", $order_price*100);//总金额,单位:分
		$unifiedOrder->setParameter("notify_url", "http://".$_SERVER['SERVER_NAME']."/wx_notify_url.php");//通知地址
		$unifiedOrder->setParameter("trade_type", "JSAPI");//交易类型
		//非必填参数，商户可根据实际情况选填
		//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
		//$unifiedOrder->setParameter("device_info","XXXX");//设备号
		//$unifiedOrder->setParameter("attach","XXXX");//附加数据
		//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
		//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
		//$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
		//$unifiedOrder->setParameter("openid","XXXX");//用户标识
		//$unifiedOrder->setParameter("product_id","XXXX");//商品ID
		
		$prepay_id = $unifiedOrder->getPrepayId();
		//=========步骤3：使用jsapi调起支付============
		$jsApi->setPrepayId($prepay_id);
		
		$jsApiParameters = $jsApi->getParameters();
		//exit($jsApiParameters);
		
		success( $jsApiParameters, '成功', 0, array('order_sn'=>$_SESSION['order_sn']) );
		$_SESSION['coffee_order_sn'] = '';
		$_SESSION['coffee_order_price'] = '';
		$_SESSION['coffee_order_body'] = '';
	}
	
	//自动作业
	public function auto_cron() {
		// $this->auto_shouhuo();
		$this->auto_audit_refund();
	}

	//找出订单状态为“已发货”的订单，发货超过7天的，系统确认收货
	public function auto_shouhuo() {
		/*
		$now - $shipping_time >= 7*24*3600;
		$now - 7*24*3600 >= $shipping_time;
		*/
		//echo time();
		$now = time();
		$day7 = $now - (($this->configs['auto_shouhuo_days']-1)*24*3600);
		//$sql = "SELECT * FROM jf_order WHERE shipping_time<='{$day7}' AND status='2' AND add_time>'1462320947'";
		$sql = "SELECT * FROM jf_order WHERE shipping_time<='{$day7}' AND status='2'";
		echo $sql;
		$rs = $this->db->get_results($sql);
		//print_r($rs);
		//exit;
		if ($rs) {
			foreach ($rs as $k => $order) {
				$this->order_mod->shouhuo($order->id, $order->member_id);
				//exit;
			}
		}
	}

	//确认收货
	public function order_shouhuo() {
		$order_id = (isset($_POST['id']) && trim($_POST['id'])) ? intval($_POST['id']) : 0;
		$order = $this->order_mod->shouhuo($order_id);
		success('ok');
	}

	//店铺订单列表
	//0：未支付，1：已支付，2：已发货，3：完成（已收货），-1：取消，-2：退款，-3：退货
	public function shop_order() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		$where = "o.shop_id='{$this->shop_id}'";
		if (isset($_GET['status'])) {
			if (strlen($_GET['status'])) {
				$status = intval($_GET['status']);
				//未支付的摇一摇订单，不要显示出来，因为用户会点击“支付”按钮支付
				if ($status==0) {
					$where .= " AND o.status='{$status}' AND prize_id=0";
				} else {
					$where .= " AND o.status='{$status}'";
				}
			} else {
				$where .= " AND ((o.status=0 AND prize_id=0) OR o.status<>0) ";
			}
		} else { //搜索全部，将没有支付的摇一摇订单剔除
			$where .= " AND ((o.status=0 AND prize_id=0) OR o.status<>0) ";
			//exit;
		}
		/*
		if (isset($_GET['status'])) {
			if (strlen($_GET['status'])) {
				$status = intval($_GET['status']);
				$where .= " AND o.status='{$status}'";
			}
		}
		*/
		$sql = "SELECT o.* FROM jf_order o
			WHERE {$where} ORDER BY o.id DESC LIMIT {$offset},{$pagesize}";
		//echo $sql;
		$orders = $this->db->get_results($sql);
		if ($orders) {
			foreach ($orders as $k=>$o) {
				$sql = "SELECT * FROM jf_order_goods WHERE order_id='{$o->id}'";
				$goods = $this->db->get_results($sql);
				$goods = add_domain_deep($goods, array("goods_pic"));
				$orders[$k]->goods = $goods;
			}
		}
		success($orders);
	}

	public function get_shipping_company_and_goods() {
		$order_id = (isset($_GET['order_id']) && trim($_GET['order_id'])) ? intval($_GET['order_id']) : 0;
		//$sql = "SELECT pinyin, name FROM jf_shipping_company ORDER BY sort ASC, name ASC";
		//$shippings = $this->db->get_results($sql);
		$shippings = $this->shipping_company(false);
		$sql = "SELECT goods_id as id, goods_name, goods_pic, qrcode, spec, quantity FROM jf_order_goods
			WHERE shop_id='{$this->shop_id}' AND order_id='{$order_id}'";
		$goods = $this->db->get_results($sql);
		$goods = add_domain_deep($goods, array("goods_pic"));
		success(array("shipping_company"=>$shippings, "goods"=>$goods));
	}
	
	//我的发现
	public function article() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		if ($this->member_id<=0) error('请登录', -100);
		$sql = "SELECT * FROM jf_article WHERE member_id='{$this->member_id}' ORDER BY sort ASC, id DESC LIMIT {$offset}, {$pagesize}";
		$articles = $this->db->get_results($sql);
		if ($articles) {
			foreach ($articles as $k=>$article) {
				$sql = "SELECT pic FROM jf_article_pic WHERE article_id='{$article->id}' ORDER BY id ASC LIMIT 3";
				$pics = $this->db->get_results($sql);
				$articles[$k]->pics = $pics;
				$sql = "SELECT goods_id FROM jf_article_goods WHERE article_id='{$article->id}' ORDER BY id ASC";
				$goods = $this->db->get_results($sql);
				$articles[$k]->goods = $goods;
				$articles[$k]->add_time = get_time_word($article->add_time);
			}
		}
		
		success($articles);
	}
	
	//删除我的发现
	public function article_delete() {
		$id = (isset($_POST['id']) && trim($_POST['id'])) ? intval($_POST['id']) : 0;
		$sql = "DELETE FROM jf_article WHERE member_id='{$this->member_id}' AND id='{$id}'";
		$this->db->query($sql);
		success('ok');
	}

	//获取快递公司列表
	public function shipping_company($success=true) {
		$sql = "SELECT pinyin, name FROM jf_shipping_company ORDER BY sort ASC, name ASC";
		$results = $this->db->get_results($sql);
		if ($success) {
			success($results);
		} else {
			return $results;
		}
	}

	//根据标签码获取商品ID
	public function get_goods_id_from_qrcode() {
		$code = (isset($_GET['code']) && trim($_GET['code'])) ? trim($_GET['code']) : '';
		$sql = "SELECT goods_id FROM jf_factory_code WHERE code='{$code}' ORDER BY id DESC";
		$goods_id = $this->db->get_var($sql);
		if ($goods_id) {
			success($goods_id);
		} else {
			error('该标签没有绑定到商品');
		}
	}

	//去转义
	public function unTurn($val) {
		if (is_array($val)) {
			$val = array_map('unTurn', $val);
		}else {
			$val = stripslashes($val);
		}
		return $val;
	}
	

	//退款退货申请
	public function refund() {
		$order_id = (isset($_POST['order_id']) && trim($_POST['order_id'])) ? intval($_POST['order_id']) : 0;
		$type = (isset($_POST['type']) && trim($_POST['type'])) ? intval($_POST['type']) : 0; //1:退款, 2:退货
		//$price = (isset($_POST['price']) && floatval($_POST['price'])) ? floatval($_POST['price']) : 0;
		$reason = (isset($_POST['reason']) && trim($_POST['reason'])) ? trim($_POST['reason']) : '';
		$memo = (isset($_POST['memo']) && trim($_POST['memo'])) ? trim($_POST['memo']) : '';
		$pic1 = (isset($_POST['pic1']) && trim($_POST['pic1'])) ? trim($_POST['pic1']) : '';
		$pic2 = (isset($_POST['pic2']) && trim($_POST['pic2'])) ? trim($_POST['pic2']) : '';
		$pic3 = (isset($_POST['pic3']) && trim($_POST['pic3'])) ? trim($_POST['pic3']) : '';
		if (!$order_id) error('无效的订单号');
		
		$sql = "SELECT order_sn FROM jf_order WHERE id='{$order_id}' AND member_id='{$this->member_id}' AND status>0";
		$order = $this->db->get_row($sql);
		if (!$order) error('订单不存在!');
		
		//把parent_order_sn设置为order_sn
		//$sql = "UPDATE jf_order SET parent_order_sn='{$order->order_sn}' WHERE id='{$order_id}'";
		//$this->db->query($sql);
		
		$sql = "SELECT member_id, mobile, total_price, pay_method, parent_order_sn, trade_no, status FROM jf_order WHERE id='{$order_id}'";
		//exit($sql);
		$order = $this->db->get_row($sql);
		$out_refund_no = generate_order_sn();
		
		$pic1 = upload_one_file('uploadfiles/refund', 'pic1');
		$pic2 = upload_one_file('uploadfiles/refund', 'pic2');
		$pic3 = upload_one_file('uploadfiles/refund', 'pic3');
		
		$sql = "INSERT INTO jf_order_refund(order_id, member_id, pay_method, out_refund_no, type, price, reason, memo, pic1, pic2, pic3, status, add_time)
			VALUES ('{$order_id}', '{$order->member_id}', '{$order->pay_method}', '{$out_refund_no}', '{$type}', '{$order->total_price}',
			'{$reason}', '{$memo}', '{$pic1}', '{$pic2}', '{$pic3}', '0', '".time()."')";
		$this->db->query($sql);
		
		//20160428 by @jsong 要求任何状态都需要厂家审核
		//$r = "原因：{$reason}";
		//if ($memo) $r .= chr(13).chr(10)."说明：{$memo}";
		$this->order_return_goods();
		//success('您的申请已提交，请耐心等待商家处理');
		/*
		if ($order->status>1) { //已支付已发货订单需要厂家审核
			$this->order_return_goods("原因：{$reason}".chr(13).chr(10)."说明：{$memo}");
			exit;
		}
		$id = $this->db->insert_id;
		$sql = "UPDATE jf_order SET ask_refund_time='".time()."' WHERE id='{$order_id}'";
		$this->db->query($sql);
		$this->_refund($order_id, $order->parent_order_sn, $order->trade_no, $order->total_price, $order->pay_method, $out_refund_no, $id, $order->member_id, $order->mobile);
		send_sms($order->mobile, "您在优必上申请的退款已到账");
		success('订单已退款，请及时检查您的第三方支付平台的账户，若未收到款项请尽快联系我们');
		*/
	}
	
	//第三方退款
	private function _refund($order_id, $order_sn, $trade_no, $total_price, $pay_method, $out_refund_no, $refund_id, $member_id=0, $mobile='') {
		if ($pay_method=='wxpay' || $pay_method=='wxpay_h5') {
			if ($pay_method=='wxpay') {
				include_once(FRAMEWORK_PATH . "/class/wxapi/RefundAppHelper/WxPay.Api.php");
			} else {
				include_once(FRAMEWORK_PATH . "/class/wxapi/RefundWxHelper/WxPay.Api.php");
			}
			$input = new WxPayRefund();
			if ($trade_no!='') {
				$input->SetTransaction_id($trade_no); //微信订单号
			} else {
				$input->SetOut_trade_no($order_sn); //原订单号
			}
			$input->SetTotal_fee($total_price*100); //订单金额，单位分
			$input->SetRefund_fee($total_price*100); //退款金额
			$input->SetOp_user_id(WxPayConfig::MCHID); //操作员账号，一般为商户号
			$input->SetOut_refund_no($out_refund_no); //退款订单号
			$data = WxPayApi::refund($input);
			//foreach ($data as $k=>$v) echo "<font color='#f00;'>$k</font> : $v<br/>";exit;
			if ($data["return_code"]=='SUCCESS') {
				if ($data["result_code"]=='SUCCESS') {
					$sql = "UPDATE jf_order_refund SET status='1' WHERE id='{$refund_id}'";
					$this->db->query($sql);
					$sql = "UPDATE jf_order SET status='-2' WHERE id='{$order_id}'";
					$this->db->query($sql);
				} else {
					error($data["err_code_des"]);
				}
			} else {
				error($data["return_msg"]);
			}
		} else if ($pay_method=='alipay') {
			require_once(FRAMEWORK_PATH . "/class/alipay/alipay.config.php");
			require_once(FRAMEWORK_PATH . "/class/alipay/lib/alipay_refund_nopwd_service.php");
			$seller_email = $alipay_config['seller_email']; //卖家支付宝帐户
			$refund_date = date('Y-m-d H:i:s'); //退款当天日期
			$batch_no = date('YmdHis'); //批次号, 格式：当天日期[8位]+序列号[3至24位]，如：201008010000001
			$batch_num = 1; //退款笔数
			//必填，参数detail_data的值中，“#”字符出现的数量加1，最大支持1000笔（即“#”字符出现的数量999个）
			$detail_data = "{$trade_no}^{$total_price}^买家主动退款"; //退款详细数据
			//必填，具体格式请参见接口技术文档，单笔退款数据集格式：原付款支付宝交易号^退款总金额^退款理由
			$notify_url = "http://".$_SERVER['SERVER_NAME']."/notify_url_refund.php"; //异步通知页面
			//构造要请求的参数数组，无需改动
			$parameter = array(
				//接口名称，不需要修改
				"service"			=> "refund_fastpay_by_platform_nopwd",
				//获取配置文件(alipay_config.php)中的值
				"partner"			=> trim($alipay_config['partner']),
				"notify_url"		=> $notify_url,
				"_input_charset"	=> trim(strtolower($alipay_config['input_charset'])),
				//必填参数
				"refund_date"		=> $refund_date,
				"batch_no"			=> $batch_no,
				"batch_num"			=> $batch_num,
				"detail_data"		=> $detail_data
			);
			//构造请求函数, 配置环境须支持SSL
			$alipay = new alipay_refund_nopwd_service($parameter, $alipay_config['key'], $alipay_config['sign_type_refund']);
			$url = $alipay->create_url();
			$data = file_get_contents($url);
			$nodeIs_success = '';
			$nodeError_code = '';
			$obj = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
			$obj = (array)$obj;
			//writeLog(json_encode($obj));
			if (isset($obj['is_success'])) $nodeIs_success = $obj['is_success']; //获取成功标识is_success
			if (isset($obj['error'])) $nodeError_code = $obj['error']; //获取错误代码 error
			if ($nodeIs_success=="T") {
				$sql = "UPDATE jf_order_refund SET status='1' WHERE id='{$refund_id}'";
				$this->db->query($sql);
				$sql = "UPDATE jf_order SET status='-2' WHERE id='{$order_id}'";
				$this->db->query($sql);
			} else {
				error($nodeError_code);
			}
		} else if ($pay_method=='yue') {
			$sql = "UPDATE member SET money=money+{$total_price} WHERE member_id='{$member_id}'";
			$this->db->query($sql);
			$sql = "UPDATE jf_order_refund SET status='1' WHERE id='{$refund_id}'";
			$this->db->query($sql);
			$sql = "UPDATE jf_order SET status='-2' WHERE id='{$order_id}'";
			$this->db->query($sql);
		}
	}

	//退货退款申请，1:退款, 2:退货
	public function order_return_goods($reason='') {
		$order_id = (isset($_POST['order_id']) && trim($_POST['order_id'])) ? intval($_POST['order_id']) : 0;
		$type = (isset($_POST['type']) && trim($_POST['type'])) ? intval($_POST['type']) : 0; //1:退款, 2:退货
		if (!$reason) $reason = (isset($_POST['reason']) && trim($_POST['reason'])) ? trim($_POST['reason']) : '';
		if (!$order_id) error('数据错误');
		/*
		//remark by ajsong 2016-7-13 yidian的数据库操作
		$sql = "SELECT factory_shop_id, s.member_id as shop_member_id, m.name as member_name FROM jf_order o
			LEFT JOIN jf_member m ON o.member_id=m.id
			LEFT JOIN jf_shop s ON o.factory_shop_id=s.id
			WHERE o.id='{$order_id}'";
		$order = $this->db->get_row($sql);
		$sql = "INSERT INTO jf_order_refund (order_id, shop_id, member_id, type, reason, status, add_time)
			VALUES ('{$order_id}', '{$order->factory_shop_id}', '{$this->member_id}', '{$type}', '{$reason}', '0', '".time()."')";
		$this->db->query($sql);
		*/
		$sql = "SELECT m.name as member_name FROM jf_order o LEFT JOIN jf_member m ON o.member_id=m.id WHERE o.id='{$order_id}'";
		$order = $this->db->get_row($sql);
		
		$sql = "UPDATE jf_order SET ask_refund_time='".time()."' WHERE id='{$order_id}'";
		$this->db->query($sql);
		
		/*
		//remark by ajsong 2016-7-13 商富商城没有厂家，因此不可以发短信
		//发送短信、推送
		$member_id = -1;
		$notify = '';
		$sms = array();
		$template_id = 0;
		if ($type==1) {
			$member_id = $order->shop_member_id;
			$notify = "客户{$order->member_name}提出退款申请，请及时审核";
			$sms = array($order->member_name);
			$template_id = 83100;
		} else {
			$member_id = $order->shop_member_id;
			$notify = "客户{$order->member_name}提出退货申请，请及时审核";
			$sms = array($order->member_name);
			$template_id = 83099;
		}
		$this->send_notify_sms($notify, $member_id, true, $sms, $template_id);
		*/
		
		$str = '退款';
		if ($type==2) $str = '退货';
		success("ok", "{$str}申请已提交，请耐心等待商家处理");
	}

	//自动确认退货退款审核，24小时后
	public function auto_audit_refund() {
		/*
		$now - $add_time >= 7*24*3600;
		$now - 7*24*3600 >= $add_time;
		*/
		//echo time();
		$now = time();
		$day7 = $now - 7*24*3600;
		$sql = "SELECT * FROM jf_order_refund WHERE add_time<='{$day7}' AND status='0' AND add_time>'0'";
		//echo $sql;
		$rs = $this->db->get_results($sql);
		//print_r($rs);
		//exit;
		if ($rs) {
			foreach ($rs as $k => $refund) {
				$this->order_check_return_goods($refund->order_id, '自动确认退货或退款', 1);
			}
			echo "SUCCESS";
		}
	}

	//退货退款审核，1:退款, 2:退货
	public function order_check_return_goods($order_id=0, $reason='', $status=1) {
		if (!$order_id) {
			$order_id = (isset($_POST['order_id']) && trim($_POST['order_id'])) ? intval($_POST['order_id']) : 0;
			$reason = (isset($_POST['reason']) && trim($_POST['reason'])) ? trim($_POST['reason']) : '';
			$status = (isset($_POST['status']) && trim($_POST['status'])) ? intval($_POST['status']) : 0;
		}
		if ($order_id) {
			//判断是退款还是退货
			$sql = "SELECT type FROM jf_order_refund WHERE order_id='{$order_id}' ORDER BY id DESC";
			$type = $this->db->get_var($sql);
			
			$sql = "SELECT o.*, s.member_id as shop_member_id FROM jf_order o
				LEFT JOIN jf_shop s ON factory_shop_id=s.id
				WHERE o.id='{$order_id}'";
			$order = $this->db->get_row($sql);
			
			if ($status==1) {
				$sql = "SELECT id, out_refund_no FROM jf_order_refund WHERE order_id='{$order_id}' ORDER BY id DESC";
				$refund = $this->db->get_row($sql);
				$this->_refund($order_id, $order->parent_order_sn, $order->trade_no, $order->total_price, $order->pay_method, $refund->out_refund_no, $refund->id, $order->member_id, $order->mobile);
				if ($type==1) {
					$reason = "已退款";
				} else {
					$sql = "UPDATE jf_order SET status='-3' WHERE id='{$order_id}'";
					$this->db->query($sql);
					$sql = "SELECT factory_shop_id FROM jf_order WHERE id='{$order_id}'";
					$shop_id = $this->db->get_var($sql);
					$sql = "SELECT return_province, return_city, return_district, return_address, return_name, return_mobile FROM jf_shop WHERE id='{$shop_id}'";
					$row = $this->db->get_row($sql);
					$reason = "退货地址：{$row->return_province}{$row->return_city}{$row->return_district}{$row->return_address}，联系人：{$row->return_name}，电话：{$row->return_mobile}";
				}
				//扣减退货退款后店铺的佣金 by willson 2016/5/4
				$this->_reduce_order_commission($order_id);
			}
			$sql = "UPDATE jf_order_refund SET status='{$status}', audit_time='".time()."', audit_memo='{$reason}' WHERE order_id='{$order_id}'";
			$this->db->query($sql);
			
			//发送短信、推送
			$member_id = -1;
			$notify = '';
			$sms = array();
			$template_id = 0;
			if ($status==1) {
				if ($type==1) {
					$member_id = $order->member_id;
					$notify = "您的订单{$order->order_sn}退款成功，退款金额为{$order->total_price}元";
					$sms = array($order->order_sn, "{$order->total_price}元");
					$template_id = 83095;
				} else {
					$member_id = $order->member_id;
					$notify = "您的订单{$order->order_sn}退货成功";
					$sms = array($order->order_sn);
					$template_id = 83101;
				}
			} else {
				if ($type==1) {
					$member_id = $order->member_id;
					$notify = "您申请的退款请求失败，请联系卖家";
					$template_id = 83103;
				} else {
					$member_id = $order->member_id;
					$notify = "您申请的退货请求失败，请联系卖家";
					$template_id = 83102;
				}
			}
			$this->send_notify_sms($notify, $member_id, true, $sms, $template_id);
			
			if ($status==1 && $type==1) {
				switch ($order->pay_method) {
					case 'wxpay':
					case 'wxpay_h5':
					case 'alipay':
						success('订单已退款，请及时检查您的第三方支付平台的账户，若未收到款项请尽快联系我们');
						break;
					case 'yue':
						if ($order->member_id == $this->member_id) {
							success('订单已退款，请在会员中心查看您的余额是否已到账');
						}
						break;
				}
			}
		}
		success('ok');
	}

	//退货退款成功后，扣减店铺的佣金
	private function _reduce_order_commission($order_id) {
		$sql = "SELECT * FROM jf_order_commission WHERE order_id='{$order_id}' AND status=1";
		$commissions = $this->db->get_results($sql);
		if ($commissions) {
			foreach ($commissions as $k => $commission) {
				$money = $commission->commission;
				if ($money) {
					$sql = "SELECT total_income, can_withdraw_money FROM jf_shop WHERE id='{$commission->shop_id}'";
					$shop = $this->db->get_row($sql);
					if ($shop) {
						if ($shop->total_income>=$money) {
							$shop->total_income = $shop->total_income - $money;
						} else {
							$shop->total_income = 0;
						}
						if ($shop->can_withdraw_money>=$money) {
							$shop->can_withdraw_money = $shop->can_withdraw_money - $money;
						} else {
							$shop->can_withdraw_money = 0;
						}
						$sql = "UPDATE jf_shop SET total_income='{$shop->total_income}',
							can_withdraw_money='{$shop->can_withdraw_money}' WHERE id='{$commission->shop_id}'";
						$this->db->query($sql);
					}
				}
			}
		}
		$sql = "UPDATE jf_order_commission SET status='-1' WHERE order_id='{$order_id}'";
		$this->db->query($sql);
	}

	//通过会员id读取头像
	public function get_avatar() {
		$members = "";
		$avatar = '';
		$nick_name = '';
		$ids = '';
		$member_ids = (isset($_GET['member_id']) && trim($_GET['member_id'])) ? $_GET['member_id'] : '';
		if ($member_ids) {
			$arr = explode(',', $member_ids);
			foreach ($arr as $value) {
				if (is_numeric($value)) $ids .= ','.$value;
			}
			$ids = trim($ids, ',');
			$sql = "SELECT m.id, m.name, m.avatar, m.real_name, m.member_type,
				m.mobile as member_mobile, m.qq as member_qq, m.weixin as member_weixin,
				s.mobile as shop_mobile, s.qq as shop_qq, s.weixin as shop_weixin,
				s.name as shop_name, s.avatar as shop_avatar, s.status
				FROM jf_member m LEFT JOIN jf_shop s ON m.id=s.member_id
				WHERE m.id IN ({$ids})";
			$members = $this->db->get_results($sql);
			if ($members) {
				foreach ($members as $k=>$m) {
					$obj = new stdClass();
					$obj->id = $m->id;
					/*/
					$obj->name = $m->name;
					$obj->avatar = $m->avatar;
					$obj->mobile = $m->member_mobile;
					$obj->qq = $m->member_qq;
					$obj->weixin = $m->member_weixin;
					//*/
					if ($m->member_type==3) {
						$obj->name = $m->shop_name;
						$obj->avatar = $m->shop_avatar;
						$obj->mobile = $m->shop_mobile;
						$obj->qq = $m->shop_qq;
						$obj->weixin = $m->shop_weixin;
					} else {
						if ($m->real_name) {
							$obj->name = $m->real_name;
						} else {
							$obj->name = $m->name;
						}
						$obj->avatar = $m->avatar;
						$obj->mobile = $m->member_mobile;
						$obj->qq = $m->member_qq;
						$obj->weixin = $m->member_weixin;
					}
					//*/
					$members[$k] = $obj;
				}
				$members = add_domain_deep($members, array("avatar"));
			}
		}
		success($members);
	}

	//通过会员id获取会员的联系方式、微信、qq（非常不安全的做法）
	public function get_contact() {
		$mobile = $qq = $weixin = "";
		$member_id = (isset($_GET['member_id']) && trim($_GET['member_id'])) ? intval($_GET['member_id']) : 0;
		if ($member_id) {
			//先读取店铺
			$sql = "SELECT s.mobile, s.qq, s.weixin FROM jf_shop s LEFT JOIN jf_member m ON s.member_id=m.id
				WHERE m.id='{$member_id}'";
			$row = $this->db->get_row($sql);
			//店铺的不存在，读取会员的
			if (!$row) {
				$sql = "SELECT mobile, qq, weixin FROM jf_member WHERE id='{$member_id}'";
				$row = $this->db->get_row($sql);
			}
			if ($row) {
				$mobile = $row->mobile;
				$qq = $row->qq;
				$weixin = $row->weixin;
			}
		}
		success(array("mobile"=>$mobile, "qq"=>$qq, "weixin"=>$weixin));
	}

	//重新加载会员的SESSION，一般在设置了大量的个人信息后
	private function _reload_session_info() {
		$sql = "SELECT * FROM {$this->tbp}member WHERE id='{$this->member_id}'";
		$member = $this->db->get_row($sql);
		if ($member) {
			//导致shop_id丢失
			$_SESSION['member'] = $member;
			return true;
		}  else {
			return false;
		}
	}

	//已邀请用户
	public function my_invite_user() {
		$members = null;
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		if ($this->member_id) {
			$sql = "SELECT m.id, m.name, m.avatar, m.reg_time, m.mobile
				FROM jf_member m
				WHERE m.parent_id='{$this->member_id}' ORDER BY m.id DESC
				LIMIT {$offset}, {$pagesize}";
			$members = $this->db->get_results($sql);
			if ($members) {
				foreach ($members as $k => $member) {
					if (!$member->name) {
						$members[$k]->name = $member->mobile;
					}
					$members[$k]->reg_time = date("Y-m-d", $member->reg_time);
				}
				$members = add_domain_deep($members, array("avatar"));
			}
		}
		success($members);
	}

	//财富明细
	public function commission_history() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		$commissions = null;
		if ($this->member_id) {
			$sql = "SELECT id, commission, memo,status, add_time FROM jf_member_commission
				WHERE member_id='{$this->member_id}' ORDER BY id DESC
				LIMIT {$offset}, {$pagesize}";
			$commissions = $this->db->get_results($sql);
			if ($commissions) {
				foreach ($commissions as $k => $commission) {
					$commissions[$k]->add_time = date("Y-m-d H:i:s", $commission->add_time);
				}
				//$members = add_domain_deep($members, array("avatar"));
			}
		}
		success($commissions);
	}

	//我的店员列表
	public function clerk() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		$clerks = null;
		if ($this->member_id && $_SESSION['member']->member_type==3) {
			//店员
			$sql = "SELECT * FROM jf_member WHERE shopowner_id='{$this->member_id}' ORDER BY id DESC LIMIT {$offset}, {$pagesize}";
			$clerks = $this->db->get_results($sql);
			//店员所带来的订单总额
			if($clerks){
				foreach ($clerks as $key => $val) {
					$sql = "SELECT sum(total_price) FROM jf_order WHERE member_id in (SELECT id 
						FROM jf_member WHERE parent_id = {$val->id} OR id = {$val->id}) 
						AND status > 0 ORDER BY total_price DESC";
					// $sql = "SELECT sum(total_price) FROM jf_order WHERE member_id='{$val->id}'";
					$val->total_price = $this->db->get_var($sql);
					// print_r($sql);exit;
				}
			}
		}
		success($clerks);
	}
	
	//店员带来订单
	public function clerk_order() {
		$clerks = null;
		$where = '';
		$nav = '';
		$empt = '';
		// $offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		// $pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		$clerk_id = (isset($_GET['clerk_id']) && trim($_GET['clerk_id'])) ? intval($_GET['clerk_id']) : 0;
		$sign = (isset($_GET['sign']) && trim($_GET['sign'])) ? trim($_GET['sign']) : '';
		$starttime = (isset($_GET['starttime']) && trim($_GET['starttime'])) ? trim($_GET['starttime']) : 0;
		$endtime = (isset($_GET['endtime']) && trim($_GET['endtime'])) ? trim($_GET['endtime']) : 0;
		$starttime = strtotime($starttime);
		$endtime = strtotime($endtime);
		$clerk_order = null;
		//判断该店员是否属于该店张
		$sql = "SELECT * FROM jf_member WHERE shopowner_id = {$this->member_id} AND id = {$clerk_id}";
		$sure = $this->db->get_var($sql);
		if ($this->member_id && $clerk_id && $sure) {
			if($starttime>0 && $endtime>0){
				$where .= " AND o.add_time>={$starttime} AND o.add_time<={$endtime}";
			}
			//分页
			// $this->ezr->num_results_per_page=5;
			$this->setpages(array('endtime'=>$endtime,'starttime'=>$starttime,'clerk_id'=>$clerk_id));
			//店员所带来的订单
			$sql = "SELECT id FROM jf_member WHERE parent_id='{$clerk_id}'";
			$a = $this->db->get_results($sql);
			//店员带来的订单（包含自身订单）
			$where_a = "{$clerk_id} ,";
			if($a){
				foreach ($a as $key => $val) {
					$where_a .= "{$val->id} ,";
				}
			}
			$where_a =substr($where_a, 0 , -1);
			$sql = "SELECT o.order_sn ,o.add_time ,o.total_price FROM jf_order o 
					WHERE member_id in ({$where_a}) AND o.status > 0 {$where}
					ORDER BY o.add_time DESC";
			$clerk_order = $this->ezr->get_results($sql);
			$nav = $this->ezr->get_navigation();

			if ($clerk_order) {
				foreach ($clerk_order as $k => $row) {
					$clerk_order[$k]['add_time'] = date("m-d", $row['add_time']);
				}
			}
			if($starttime && $endtime){
				$starttime = date("Y-m-d", $starttime);
				$endtime = date("Y-m-d", $endtime);
			}
		}else{
			$empt = '请确认是否是所属店员！';
		}
		
		success(array("clerk_order"=>$clerk_order, "clerk_id"=>$clerk_id, "sign"=>$sign, 
			"nav"=>$nav,"starttime"=>$starttime,"endtime"=>$endtime ,'empt'=>$empt));
}
	
	//我的店员
	public function sells() {
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		$rs = null;
		if ($this->member_id && $_SESSION['member']->member_type==3) {
			$sql = "SELECT * FROM jf_member WHERE shopowner_id='{$this->member_id}' ORDER BY id DESC LIMIT {$offset}, {$pagesize}";
			$rs = $this->db->get_results($sql);
		}
		success($rs);
	}


}
